package net.gz01.wallet.web.controller.admin;

import com.jfinal.aop.Before;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;

import net.gz01.util.ZODate;
import net.gz01.wallet.common.PageRespon;
import net.gz01.wallet.web.controller.BaseController;
import net.gz01.wallet.web.interceptors.AuthInterceptor;
import net.gz01.wallet.web.model.MerchRole;
import net.gz01.wallet.web.model.OrgUser;

public class MerchRoleController extends BaseController{

	public void search(){
		render("merch/merchRoleList.html");
	}

	public void listJson(){
		Page<MerchRole> pageResult = MerchRole.dao.search(super.getSearchCondition());
		renderJson(new PageRespon(pageResult));
	}

	public void addPage(){
		render("merch/merchRoleAdd.html");
	}

	public void updatePage(){
		MerchRole role = MerchRole.dao.findById(getParaToInt("id"));
		setAttr("merchRole", role);
		render("merch/merchRoleUpdate.html");
	}

	public void alloctSourcePage(){
		MerchRole role = MerchRole.dao.findById(getParaToInt("id"));
		setAttr("merchRole", role);
		setAttr("sourceList", AuthInterceptor.getSidebar_merch_zh_CN());
		render("merch/merchRoleAlloctSource.html");
	}

	public void add(){
		MerchRole role = getModel(MerchRole.class, true);
		if(MerchRole.dao.selectByRoleName(role.getRoleName()) != null) {
			renderFail("已存在相同角色");
		} else {
			role.setUpdateDateTime(ZODate.getDateTime());
			role.save();
			renderSuccess();
		}
	}

	public void update(){
		MerchRole role = getModel(MerchRole.class, true);
		role.setUpdateDateTime(ZODate.getDateTime());
		role.update();
		renderSuccess();
	}

	@Before(Tx.class)
	public void delete(){
		Integer roleId = getParaToInt("id");
		MerchRole.dao.deleteById(roleId);
		OrgUser.dao.setNullRoleId(roleId);
		renderSuccess(false);
	}

	public void saveAlloctSource(){
		String[] sourceGroup = getParaValues("sourceGroup");
		String[] sourceUrl = getParaValues("sourceUrl");
		if(sourceGroup == null){
			sourceGroup = new String[]{};
		}
		if(sourceUrl == null){
			sourceUrl = new String[]{};
		}
		MerchRole role = getModel(MerchRole.class ,true);
		String group = "";
		for (String tmp : sourceGroup) {
			group += tmp + ",";
		}
		String url = "";
		for (String tmp : sourceUrl) {
			url += tmp + ",";
		}
		role.setSourceGroup(group);
		role.setSourceUrl(url);
		role.update();
		renderSuccess();
	}

}
